package org.example.codetrail.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.google.gson.*;
import org.apache.catalina.connector.Request;
import org.example.codetrail.pojo.Gitee.GiteeRepo;
import org.example.codetrail.pojo.Gitee.GiteeRepoContent;


public class GiteeRepoFetcher {

    private static final String GITEE_API_URL_REPOS = "https://gitee.com/api/v5/user/repos";
    //private String TOKEN = "7a72a69c1d542cfa5eaa1e54eba76afb"; // 替换为你的私人令牌
    private static final String GITEE_API_URL_CONTENTS = "https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}";

    public static GiteeRepo[] fetchAndPrintRepoNames(String TOKEN) throws IOException {
        URL url = new URL(GITEE_API_URL_REPOS);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "token " + TOKEN);

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            Gson gson = new Gson();
            GiteeRepo[] repos = gson.fromJson(content.toString(), GiteeRepo[].class);

            return repos;
        } else {
            System.err.println("请求失败，响应码: " + responseCode);
        }
        connection.disconnect();
        return null;
    }


    public static GiteeRepoContent[] getFileContent(String owner, String repo, String path, String TOKEN) throws IOException {
        URL url = new URL(GITEE_API_URL_CONTENTS.replace("{owner}", owner).replace("{repo}", repo).replace("{path}", path));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "token " + TOKEN);

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            JsonParser parser = new JsonParser();
            JsonElement jsonElement = parser.parse(content.toString());

            if (jsonElement.isJsonObject()) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                JsonArray jsonArray = new JsonArray();
                jsonArray.add(jsonObject);

                // 将 jsonArray 转换为 GiteeRepoContent 对象数组
                GiteeRepoContent[] reposContents = new Gson().fromJson(jsonArray, GiteeRepoContent[].class);
                if (reposContents != null && reposContents.length > 0) {
                    String contentStr = reposContents[0].getContent();
                    reposContents[0].setContent(Base64Utils.decodeBase64ToUtf8(contentStr));
                    return reposContents;
                }
            } else if (jsonElement.isJsonArray()) {
                JsonArray jsonArray = jsonElement.getAsJsonArray();
                // 直接处理 JSON 数组
                GiteeRepoContent[] reposContents = new Gson().fromJson(jsonArray, GiteeRepoContent[].class);
                return reposContents;
            } else {
                // 如果既不是对象也不是数组，则需要其他处理逻辑
                System.err.println("Unexpected JSON format.");
            }
        } else {
            System.err.println("请求失败，响应码: " + responseCode);
        }
        connection.disconnect();
        return new GiteeRepoContent[0]; // 返回空数组以避免 null
    }
}